<template>
  <div class="profile-container">
    <div class="page-header">
      <h2>个人中心</h2>
      <p>管理您的个人信息和账户设置</p>
    </div>

    <el-row :gutter="20">
      <!-- 左侧用户信息卡片 -->
      <el-col :span="8">
        <el-card class="user-card" shadow="hover">
          <div class="user-info">
            <div class="avatar-container">
              <el-avatar :size="100" :src="userInfo.avatar || defaultAvatar"></el-avatar>
              <div class="avatar-upload">
                <el-upload
                  action="#"
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="handleAvatarChange"
                >
                  <el-button type="primary" size="small" circle>
                    <el-icon><Edit /></el-icon>
                  </el-button>
                </el-upload>
              </div>
            </div>
            <h3 class="username">{{ userInfo.username }}</h3>
            <p class="user-role">{{ userInfo.role || '系统管理员' }}</p>
            <div class="account-status">
              <el-tag type="success" size="small">在线</el-tag>
              <span class="join-time">加入时间: {{ formatDate(userInfo.joinTime) }}</span>
            </div>

            <!-- 用户统计信息 -->
            <div class="user-stats">
              <div class="stat-item">
                <div class="stat-value">{{ userInfo.loginCount || 128 }}</div>
                <div class="stat-label">登录次数</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ formatDays(userInfo.lastLoginTime) }}</div>
                <div class="stat-label">最近登录</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ userInfo.articleCount || 12 }}</div>
                <div class="stat-label">发布文章</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧内容区域 -->
      <el-col :span="16">
        <!-- 基本资料 -->
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>基本资料</span>
            </div>
          </template>
          <el-form 
            :model="userBasicForm" 
            :rules="userBasicRules" 
            ref="userBasicFormRef" 
            label-width="100px"
            label-position="right"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="账号" prop="username">
                  <el-input v-model="userBasicForm.username" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="真实姓名" prop="realName">
                  <el-input v-model="userBasicForm.realName" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="性别" prop="gender">
                  <el-radio-group v-model="userBasicForm.gender">
                    <el-radio label="male">男</el-radio>
                    <el-radio label="female">女</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出生日期" prop="birthday">
                  <el-date-picker v-model="userBasicForm.birthday" type="date" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="手机号码" prop="phone">
                  <el-input v-model="userBasicForm.phone" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="电子邮箱" prop="email">
                  <el-input v-model="userBasicForm.email" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="政治面貌" prop="politicalStatus">
                  <el-select v-model="userBasicForm.politicalStatus">
                    <el-option label="中共党员" value="party" />
                    <el-option label="中共预备党员" value="probationary" />
                    <el-option label="共青团员" value="league" />
                    <el-option label="群众" value="masses" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="学历" prop="education">
                  <el-select v-model="userBasicForm.education">
                    <el-option label="博士" value="doctor" />
                    <el-option label="硕士" value="master" />
                    <el-option label="本科" value="bachelor" />
                    <el-option label="大专" value="college" />
                    <el-option label="高中及以下" value="highSchool" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="入党时间" prop="joinPartyDate">
                  <el-date-picker v-model="userBasicForm.joinPartyDate" type="date" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属支部" prop="partyBranch">
                  <el-select v-model="userBasicForm.partyBranch">
                    <el-option label="技术部党支部" value="tech" />
                    <el-option label="行政部党支部" value="admin" />
                    <el-option label="市场部党支部" value="market" />
                    <el-option label="财务部党支部" value="finance" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="办公地点" prop="office">
                  <el-input v-model="userBasicForm.office">
                    <template #prefix>
                      <el-icon><OfficeBuilding /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所在城市" prop="city">
                  <el-input v-model="userBasicForm.city">
                    <template #prefix>
                      <el-icon><Location /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="个人简介" prop="bio">
              <el-input v-model="userBasicForm.bio" type="textarea" rows="4" />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveBasicInfo">保存修改</el-button>
              <el-button @click="resetBasicForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { Edit, OfficeBuilding, Location } from '@element-plus/icons-vue';
import store from '@/store';

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

// 用户信息
const userInfo = reactive({
  ...store.getters.currentUser || {
    username: '张三',
    realName: '张三',
    avatar: '',
    role: '系统管理员',
    joinTime: new Date('2022-01-01'),
    lastLoginTime: new Date('2023-05-10'),
    loginCount: 128,
    articleCount: 12,
    phone: '13812345678',
    email: 'zhangsan@party.com',
    office: '党员管理中心 - 503室',
    city: '北京市'
  }
});

// 基本信息表单
const userBasicFormRef = ref(null);
const userBasicForm = reactive({
  username: userInfo.username,
  realName: userInfo.realName,
  gender: userInfo.gender || 'male',
  birthday: userInfo.birthday ? new Date(userInfo.birthday) : new Date('1990-01-01'),
  phone: userInfo.phone,
  email: userInfo.email,
  politicalStatus: userInfo.politicalStatus || 'party',
  education: userInfo.education || 'bachelor',
  joinPartyDate: userInfo.joinPartyDate ? new Date(userInfo.joinPartyDate) : new Date('2015-07-01'),
  partyBranch: userInfo.partyBranch || 'tech',
  bio: userInfo.bio || '热爱党、热爱祖国，积极参与党建活动，认真学习党的理论知识。',
  office: userInfo.office || '党员管理中心 - 503室',
  city: userInfo.city || '北京市'
});

// 基本信息表单验证规则
const userBasicRules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的电子邮箱格式', trigger: 'blur' }
  ]
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 计算距今天数
const formatDays = (date) => {
  if (!date) return '';
  const now = new Date();
  const diff = Math.floor((now - new Date(date)) / (1000 * 60 * 60 * 24));
  return `${diff}天前`;
};

// 修改头像
const handleAvatarChange = (file) => {
  const reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = () => {
    userInfo.avatar = reader.result;
    ElMessage.success('头像上传成功');
  };
};

// 保存基本信息
const saveBasicInfo = async () => {
  if (!userBasicFormRef.value) return;
  
  await userBasicFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 准备更新的用户数据
        const userData = {
          ...userInfo,
          username: userBasicForm.username,
          realName: userBasicForm.realName,
          gender: userBasicForm.gender,
          birthday: userBasicForm.birthday,
          phone: userBasicForm.phone,
          email: userBasicForm.email,
          politicalStatus: userBasicForm.politicalStatus,
          education: userBasicForm.education,
          joinPartyDate: userBasicForm.joinPartyDate,
          partyBranch: userBasicForm.partyBranch,
          bio: userBasicForm.bio,
          office: userBasicForm.office,
          city: userBasicForm.city
        };
        
        // 更新本地用户信息
        Object.assign(userInfo, userData);
        
        // 更新Vuex中的用户信息
        store.commit('setCurrentUser', userData);
        
        ElMessage.success('个人信息保存成功');
      } catch (error) {
        console.error('保存失败:', error);
        ElMessage.error('保存失败，请稍后重试');
      }
    }
  });
};

// 重置基本信息表单
const resetBasicForm = () => {
  if (userBasicFormRef.value) {
    userBasicFormRef.value.resetFields();
  }
};
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  font-size: 24px;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-header p {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.user-card {
  margin-bottom: 20px;
  text-align: center;
}

.avatar-container {
  position: relative;
  display: inline-block;
  margin: 20px 0;
}

.avatar-upload {
  position: absolute;
  right: 0;
  bottom: 0;
}

.username {
  font-size: 20px;
  margin: 10px 0 5px;
  color: #303133;
}

.user-role {
  font-size: 14px;
  color: #606266;
  margin: 0 0 10px;
}

.account-status {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 15px;
}

.join-time {
  margin-left: 10px;
  font-size: 12px;
  color: #909399;
}

.user-stats {
  display: flex;
  justify-content: space-around;
  margin: 20px 0;
  padding: 15px 0;
  border-top: 1px solid #EBEEF5;
  border-bottom: 1px solid #EBEEF5;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 18px;
  color: #303133;
  font-weight: bold;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
}
</style> 